<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音频上传</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"
        integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        /* 全局样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f0f2f5, #e1e5ea);
            /* 渐变背景 */
            color: #343a40;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        .upload-container {
            width: 90%;
            max-width: 800px;
            background-color: rgba(255, 255, 255, 0.85);
            /* 半透明白色容器 */
            backdrop-filter: blur(10px);
            /* 毛玻璃效果 */
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
            /* 更柔和的阴影 */
            text-align: center;
        }

        h1 {
            color: #495057;
            /* 深灰色标题 */
            margin-bottom: 20px;
            font-weight: 500;
        }

        p {
            color: #6c757d;
        }

        /* 上传区域样式 */
        .upload-area {
            border: 2px dashed #adb5bd;
            padding: 40px;
            border-radius: 12px;
            cursor: pointer;
            margin: 20px 0;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }

        .upload-area:hover {
            border-color: #007bff;
            background-color: rgba(0, 123, 255, 0.05);
        }

        .upload-area.dragover {
            border-color: #28a745;
            background-color: rgba(40, 167, 69, 0.1);
            transform: scale(1.02);
        }

        .upload-area .drag-progress {
            position: absolute;
            bottom: 0;
            left: 0;
            height: 4px;
            background-color: #28a745;
            width: 0;
            transition: width 0.3s ease;
        }

        .upload-area i {
            font-size: 2rem;
            color: #007bff;
            margin-bottom: 15px;
            transition: transform 0.3s ease;
        }

        .upload-area.dragover i {
            transform: scale(1.2);
            color: #28a745;
        }

        .upload-area p {
            margin: 0;
            font-size: 1.1rem;
        }

        /* 文件预览 */
        .file-preview {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ced4da;
            border-radius: 8px;
            background-color: #f8f9fa;
            text-align: left;
        }

        .file-preview p {
            margin: 5px 0;
        }

        .audio-preview {
            margin-top: 15px;
            width: 100%;
            max-width: 400px;
        }

        .audio-preview audio {
            width: 100%;
            height: 40px;
            border-radius: 20px;
            background-color: #fff;
        }

        .audio-preview audio::-webkit-media-controls-panel {
            background-color: #f8f9fa;
        }

        .audio-preview audio::-webkit-media-controls-current-time-display,
        .audio-preview audio::-webkit-media-controls-time-remaining-display {
            color: #495057;
        }

        /* 按钮样式 */
        .upload-btn {
            background-color: #007bff;
            color: white;
            padding: 14px 30px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1.1rem;
            transition: background-color 0.3s ease, transform 0.2s ease;
            /* 增加点击反馈 */
        }

        .upload-btn:hover {
            background-color: #0056b3;
        }

        .upload-btn:disabled {
            background-color: #adb5bd;
            cursor: not-allowed;
        }

        .upload-btn:active {
            transform: scale(0.95);
            /* 点击时缩小 */
        }

        /* 进度条样式 */
        .progress-container {
            display: none;
            margin: 20px 0;
        }

        .progress-steps {
            list-style: none;
            padding: 0;
            margin: 0;
            display: flex;
            justify-content: space-between;
            position: relative;
            margin-bottom: 30px;
        }

        .progress-steps::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e9ecef;
            z-index: 1;
        }

        .progress-steps li {
            position: relative;
            z-index: 2;
            background: #fff;
            padding: 0 10px;
            text-align: center;
            flex: 1;
        }

        .step-number {
            width: 40px;
            height: 40px;
            line-height: 40px;
            border-radius: 50%;
            background: #fff;
            border: 2px solid #e9ecef;
            color: #6c757d;
            font-weight: bold;
            display: inline-block;
            margin-bottom: 8px;
            transition: all 0.3s ease;
        }

        .step-text {
            display: block;
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 5px;
            transition: all 0.3s ease;
        }

        .step-icon {
            display: block;
            color: #6c757d;
            font-size: 1.2rem;
            transition: all 0.3s ease;
        }

        .progress-steps li.active .step-number {
            border-color: #007bff;
            color: #007bff;
        }

        .progress-steps li.active .step-text {
            color: #007bff;
            font-weight: bold;
        }

        .progress-steps li.completed .step-number {
            background: #28a745;
            border-color: #28a745;
            color: #fff;
        }

        .progress-steps li.completed .step-text {
            color: #28a745;
        }

        .progress-steps li.completed .step-icon {
            color: #28a745;
        }

        .progress-steps li.error .step-number {
            background: #dc3545;
            border-color: #dc3545;
            color: #fff;
        }

        .progress-steps li.error .step-text {
            color: #dc3545;
        }

        .progress-steps li.error .step-icon {
            color: #dc3545;
        }

        .progress-bar {
            width: 100%;
            height: 14px;
            background-color: #e9ecef;
            border-radius: 8px;
            overflow: hidden;
        }

        .progress {
            width: 0%;
            height: 100%;
            background-color: #28a745;
            transition: width 0.3s ease;
        }

        .status-text {
            margin-top: 10px;
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
        }

        /* 加载动画 */
        .loading-spinner {
            display: none;
            width: 30px;
            height: 30px;
            margin: 20px auto;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        /* 结果显示 */
        #result {
            margin-top: 30px;
            padding: 25px;
            border-radius: 12px;
            display: none;
            text-align: left;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        }

        /* 历史记录样式 */
        #history {
            margin-top: 40px;
            padding: 25px;
            border-radius: 12px;
            background-color: #fff;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            display: none;
        }

        #history.expanded {
            display: block;
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 10px;
        }

        .history-header h2 {
            color: #495057;
            font-size: 1.5rem;
            font-weight: 500;
            margin: 0;
        }

        .history-actions {
            display: flex;
            gap: 10px;
        }

        .toggle-history {
            background: none;
            border: none;
            color: #6c757d;
            cursor: pointer;
            padding: 5px;
            transition: color 0.2s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .toggle-history:hover {
            color: #007bff;
        }

        .toggle-history i {
            font-size: 1.1rem;
            transition: transform 0.3s ease;
        }

        .toggle-history.expanded i {
            transform: rotate(180deg);
        }

        .history-group {
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            overflow: hidden;
        }

        .history-group-info {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .history-group-title {
            color: #495057;
            font-size: 1.1rem;
            font-weight: 500;
            margin: 0;
            word-break: break-word;
        }

        .history-group-time {
            color: #6c757d;
            font-size: 0.85rem;
        }

        .history-group-header {
            background-color: #f8f9fa;
            padding: 12px 15px;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            border-bottom: 1px solid #e9ecef;
        }

        .history-group-files {
            padding: 0;
            margin: 0;
            list-style: none;
            background-color: #fff;
        }

        .history-group-files li {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.2s ease;
        }

        .history-group-files li:last-child {
            border-bottom: none;
        }

        .history-group-files li:hover {
            background-color: #f8f9fa;
        }

        .file-link {
            color: #007bff;
            text-decoration: none;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            flex: 1;
            min-width: 0;
        }

        .file-link:hover {
            color: #0056b3;
            text-decoration: underline;
        }

        .file-info {
            color: #6c757d;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 15px;
            margin-left: 15px;
        }

        .file-type {
            padding: 4px 8px;
            border-radius: 4px;
            background-color: #e9ecef;
            color: #495057;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .file-size, .file-date {
            white-space: nowrap;
        }

        .delete-group {
            background: none;
            border: none;
            color: #dc3545;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .delete-group:hover {
            background-color: #dc3545;
            color: #fff;
        }

        /* 删除确认对话框样式 */
        .confirm-dialog {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #fff;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: none;
            width: 90%;
            max-width: 400px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .confirm-dialog.show {
            display: block;
            opacity: 1;
            animation: dialogFadeIn 0.3s ease;
        }

        @keyframes dialogFadeIn {
            from {
                opacity: 0;
                transform: translate(-50%, -48%);
            }
            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }

        .confirm-dialog-content {
            margin-bottom: 25px;
            text-align: center;
        }

        .confirm-dialog-content h3 {
            color: #343a40;
            margin-bottom: 12px;
            font-size: 1.3rem;
            font-weight: 500;
        }

        .confirm-dialog-content p {
            color: #6c757d;
            margin: 0;
            font-size: 1rem;
            line-height: 1.5;
        }

        .confirm-dialog-actions {
            display: flex;
            justify-content: center;
            gap: 15px;
        }

        .confirm-dialog-btn {
            padding: 10px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 1rem;
            min-width: 90px;
            font-weight: 500;
        }

        .confirm-dialog-btn.confirm {
            background-color: #dc3545;
            color: #fff;
        }

        .confirm-dialog-btn.confirm:hover {
            background-color: #c82333;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(220, 53, 69, 0.2);
        }

        .confirm-dialog-btn.cancel {
            background-color: #6c757d;
            color: #fff;
        }

        .confirm-dialog-btn.cancel:hover {
            background-color: #5a6268;
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(108, 117, 125, 0.2);
        }

        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
            display: none;
            opacity: 0;
            transition: opacity 0.3s ease;
            backdrop-filter: blur(3px);
        }

        .overlay.show {
            display: block;
            opacity: 1;
            animation: overlayFadeIn 0.3s ease;
        }

        @keyframes overlayFadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        /* 确保对话框在移动设备上也能正确显示 */
        @media (max-width: 600px) {
            .confirm-dialog {
                width: 85%;
                padding: 20px;
            }

            .confirm-dialog-content h3 {
                font-size: 1.2rem;
            }

            .confirm-dialog-content p {
                font-size: 0.95rem;
            }

            .confirm-dialog-btn {
                padding: 8px 20px;
                font-size: 0.95rem;
                min-width: 80px;
            }
        }

        /* 响应式布局 */
        @media (max-width: 600px) {
            .upload-container {
                padding: 25px;
            }

            .upload-area {
                padding: 30px;
            }

            .analysis-results {
                grid-template-columns: 1fr;
            }

            .history-group-header {
                flex-direction: column;
                gap: 10px;
            }

            .history-group-info {
                width: 100%;
            }

            .delete-group {
                align-self: flex-end;
            }

            .file-info {
                flex-direction: column;
                align-items: flex-end;
                gap: 5px;
            }

            .file-link {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }
        }
    </style>
</head>

<body>
    <div class="upload-container">
        <h1>音频上传</h1>
        <p>支持的文件格式：WAV、MP3、OGG</p>

        <div class="upload-area" id="dropZone">
            <i class="fas fa-upload"></i>
            <!-- 上传图标 -->
            <p>点击或拖拽音频文件到这里</p>
            <input type="file" id="fileInput" accept=".wav,.mp3,.ogg" style="display: none;">
            <div class="drag-progress"></div>
        </div>

        <div id="filePreview" class="file-preview" style="display: none;">
            <p><strong>文件名:</strong> <span id="fileName"></span></p>
            <p><strong>文件大小:</strong> <span id="fileSize"></span></p>
            <div class="audio-preview" id="audioPreview" style="display: none;">
                <audio id="audioPlayer" controls>
                    您的浏览器不支持音频播放
                </audio>
            </div>
        </div>

        <button class="upload-btn" id="uploadBtn" disabled>上传</button>

        <!-- 新增进度条和状态显示 -->
        <div class="progress-container" id="progressContainer">
            <ul class="progress-steps">
                <li id="step1">
                    <span class="step-number">1</span>
                    <span class="step-text">准备上传</span>
                    <span class="step-icon"><i class="fas fa-file"></i></span>
                </li>
                <li id="step2">
                    <span class="step-number">2</span>
                    <span class="step-text">上传文件</span>
                    <span class="step-icon"><i class="fas fa-upload"></i></span>
                </li>
                <li id="step3">
                    <span class="step-number">3</span>
                    <span class="step-text">处理文件</span>
                    <span class="step-icon"><i class="fas fa-cog"></i></span>
                </li>
                <li id="step4">
                    <span class="step-number">4</span>
                    <span class="step-text">完成</span>
                    <span class="step-icon"><i class="fas fa-check"></i></span>
                </li>
            </ul>
            <div class="progress-bar">
                <div class="progress" id="progressBar"></div>
            </div>
            <div class="status-text" id="statusText">准备上传...</div>
            <div class="loading-spinner" id="loadingSpinner"></div>
        </div>

        <div id="result"></div>

        <div id="history">
            <div class="history-header">
                <h2>历史记录</h2>
                <div class="history-actions">
                    <button class="refresh-btn" id="refreshHistory" title="刷新历史记录">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
            <div id="historyContent"></div>
        </div>

        <button class="toggle-history" id="toggleHistory">
            <i class="fas fa-chevron-down"></i>
            显示历史记录
        </button>

        <div class="overlay" id="overlay"></div>
        <div class="confirm-dialog" id="confirmDialog">
            <div class="confirm-dialog-content">
                <h3>确认删除</h3>
                <p>确定要删除这组历史记录吗？此操作不可恢复。</p>
            </div>
            <div class="confirm-dialog-actions">
                <button class="confirm-dialog-btn confirm" id="confirmDelete">删除</button>
                <button class="confirm-dialog-btn cancel" id="cancelDelete">取消</button>
            </div>
        </div>
    </div>

    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const uploadBtn = document.getElementById('uploadBtn');
        const result = document.getElementById('result');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const statusText = document.getElementById('statusText');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const filePreview = document.getElementById('filePreview');
        const fileNameDisplay = document.getElementById('fileName');
        const fileSizeDisplay = document.getElementById('fileSize');

        // 点击上传区域触发文件选择
        dropZone.addEventListener('click', () => {
            fileInput.click();
        });

        // 处理文件选择
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                handleFileSelection(file);
            } else {
                resetFilePreview();
            }
        });

        // 处理拖放
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('dragover');
            
            // 计算拖拽进度
            const rect = dropZone.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const progress = (x / rect.width) * 100;
            const dragProgress = dropZone.querySelector('.drag-progress');
            if (dragProgress) {
                dragProgress.style.width = `${progress}%`;
            }
        });

        dropZone.addEventListener('dragleave', (e) => {
            e.preventDefault();
            dropZone.classList.remove('dragover');
            const dragProgress = dropZone.querySelector('.drag-progress');
            if (dragProgress) {
                dragProgress.style.width = '0';
            }
        });

        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('dragover');
            const dragProgress = dropZone.querySelector('.drag-progress');
            if (dragProgress) {
                dragProgress.style.width = '0';
            }

            const file = e.dataTransfer.files[0];
            if (file) {
                handleFileSelection(file);
            } else {
                resetFilePreview();
            }
        });

        // 处理文件选择
        function handleFileSelection(file) {
            // 检查文件类型
            if (!file.type.startsWith('audio/')) {
                alert('请选择音频文件！');
                resetFilePreview();
                return;
            }

            fileNameDisplay.textContent = file.name;
            fileSizeDisplay.textContent = formatFileSize(file.size);
            filePreview.style.display = 'block';
            uploadBtn.disabled = false;

            // 创建音频预览
            const audioPreview = document.getElementById('audioPreview');
            const audioPlayer = document.getElementById('audioPlayer');
            
            // 使用 FileReader 读取文件
            const reader = new FileReader();
            reader.onload = function(e) {
                audioPlayer.src = e.target.result;
                audioPreview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }

        // 重置文件预览
        function resetFilePreview() {
            filePreview.style.display = 'none';
            document.getElementById('audioPreview').style.display = 'none';
            document.getElementById('audioPlayer').src = '';
            uploadBtn.disabled = true;
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 格式化日期时间
        function formatDateTime(dateStr) {
            const date = new Date(dateStr);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 获取文件图标
        function getFileIcon(fileType) {
            const icons = {
                'mid': 'fa-music',
                'midi': 'fa-music',
                'xml': 'fa-file-code',
                'pdf': 'fa-file-pdf',
                'png': 'fa-file-image',
                'jpg': 'fa-file-image',
                'jpeg': 'fa-file-image',
                'txt': 'fa-file-alt',
                'default': 'fa-file'
            };
            return icons[fileType] || icons.default;
        }

        // 加载历史记录
        async function loadHistory() {
            const historyContent = document.getElementById('historyContent');
            try {
                const response = await fetch('/api/history');
                if (!response.ok) {
                    throw new Error('获取历史记录失败');
                }
                
                const historyData = await response.json();
                
                if (Object.keys(historyData).length === 0) {
                    historyContent.innerHTML = '<div class="no-files">暂无历史记录</div>';
                    return;
                }

                // 按处理时间排序
                const sortedGroups = Object.entries(historyData).sort((a, b) => {
                    return new Date(b[1].createdAt) - new Date(a[1].createdAt);
                });

                historyContent.innerHTML = sortedGroups.map(([audioName, data]) => `
                    <div class="history-group" data-audio-name="${encodeURIComponent(audioName)}">
                        <div class="history-group-header">
                            <div class="history-group-info">
                                <h3 class="history-group-title">
                                    ${audioName}
                                </h3>
                                <span class="history-group-time">
                                    ${formatDateTime(data.createdAt)}
                                </span>
                            </div>
                            <button class="delete-group" onclick="showDeleteConfirm('${encodeURIComponent(audioName)}')">
                                <i class="fas fa-trash-alt"></i>
                                删除
                            </button>
                        </div>
                        <ul class="history-group-files">
                            ${data.files.map(file => `
                                <li>
                                    <a href="/output/${file.filename}" class="file-link" download>
                                        <i class="fas ${getFileIcon(file.file_type)}"></i>
                                        ${file.filename}
                                    </a>
                                    <div class="file-info">
                                        <span class="file-type">${file.file_type.toUpperCase()}</span>
                                        <span class="file-size">${formatFileSize(file.size)}</span>
                                        <span class="file-date">${formatDateTime(file.created_at)}</span>
                                    </div>
                                </li>
                            `).join('')}
                        </ul>
                    </div>
                `).join('');
            } catch (error) {
                historyContent.innerHTML = `<div class="no-files">加载失败: ${error.message}</div>`;
            }
        }

        // 切换历史记录显示/隐藏
        const toggleHistory = document.getElementById('toggleHistory');
        const history = document.getElementById('history');
        let isHistoryExpanded = false;

        toggleHistory.addEventListener('click', () => {
            isHistoryExpanded = !isHistoryExpanded;
            history.classList.toggle('expanded', isHistoryExpanded);
            toggleHistory.classList.toggle('expanded', isHistoryExpanded);
            toggleHistory.innerHTML = `
                <i class="fas fa-chevron-${isHistoryExpanded ? 'up' : 'down'}"></i>
                ${isHistoryExpanded ? '隐藏' : '显示'}历史记录
            `;
        });

        // 删除确认对话框
        const overlay = document.getElementById('overlay');
        const confirmDialog = document.getElementById('confirmDialog');
        const confirmDelete = document.getElementById('confirmDelete');
        const cancelDelete = document.getElementById('cancelDelete');
        let currentAudioName = null;

        function showDeleteConfirm(audioName) {
            currentAudioName = audioName;
            
            // 显示遮罩层和对话框
            overlay.classList.add('show');
            confirmDialog.classList.add('show');
            
            // 防止页面滚动
            document.body.style.overflow = 'hidden';
            
            // 确保对话框在视口中心
            const dialogRect = confirmDialog.getBoundingClientRect();
            const viewportHeight = window.innerHeight;
            const viewportWidth = window.innerWidth;
            
            if (dialogRect.top < 0) {
                confirmDialog.style.top = '50%';
            }
            
            if (dialogRect.left < 0) {
                confirmDialog.style.left = '50%';
            }
        }

        function hideDeleteConfirm() {
            // 隐藏遮罩层和对话框
            overlay.classList.remove('show');
            confirmDialog.classList.remove('show');
            
            // 重置对话框位置
            confirmDialog.style.top = '50%';
            confirmDialog.style.left = '50%';
            
            // 清除当前音频名称
            currentAudioName = null;
            
            // 恢复页面滚动
            document.body.style.overflow = '';
        }

        // 点击遮罩层关闭对话框
        overlay.addEventListener('click', hideDeleteConfirm);

        // 点击取消按钮关闭对话框
        cancelDelete.addEventListener('click', hideDeleteConfirm);

        // 点击确认按钮删除记录
        confirmDelete.addEventListener('click', async () => {
            if (!currentAudioName) return;

            try {
                const response = await fetch(`/api/history/${currentAudioName}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    throw new Error('删除失败');
                }

                hideDeleteConfirm();
                loadHistory();
            } catch (error) {
                alert(`删除失败: ${error.message}`);
            }
        });

        // 添加键盘事件监听
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && overlay.classList.contains('show')) {
                hideDeleteConfirm();
            }
        });

        // 监听窗口大小变化，确保对话框始终在视口中心
        window.addEventListener('resize', () => {
            if (overlay.classList.contains('show')) {
                const dialogRect = confirmDialog.getBoundingClientRect();
                const viewportHeight = window.innerHeight;
                const viewportWidth = window.innerWidth;
                
                if (dialogRect.top < 0) {
                    confirmDialog.style.top = '50%';
                }
                
                if (dialogRect.left < 0) {
                    confirmDialog.style.left = '50%';
                }
            }
        });

        // 页面加载完成后加载历史记录
        window.addEventListener('load', loadHistory);

        // 刷新按钮点击事件
        document.getElementById('refreshHistory').addEventListener('click', loadHistory);

        // 更新进度条和状态
        function updateProgress(progress, status) {
            progressBar.style.width = `${progress}%`;
            statusText.textContent = status;
        }

        // 更新步骤状态
        function updateStep(stepNumber, status) {
            const steps = document.querySelectorAll('.progress-steps li');
            steps.forEach((step, index) => {
                step.classList.remove('active', 'completed', 'error');
                const icon = step.querySelector('.step-icon i');
                
                if (index + 1 < stepNumber) {
                    // 已完成步骤
                    step.classList.add('completed');
                    icon.className = 'fas fa-check';
                } else if (index + 1 === stepNumber) {
                    // 当前步骤
                    step.classList.add('active');
                    if (status === 'processing') {
                        icon.className = 'fas fa-spinner fa-spin';
                    } else if (status === 'error') {
                        step.classList.add('error');
                        icon.className = 'fas fa-times';
                    } else {
                        icon.className = icon.getAttribute('data-icon') || 'fas fa-check';
                    }
                }
            });
        }

        // 重置步骤状态
        function resetSteps() {
            const steps = document.querySelectorAll('.progress-steps li');
            steps.forEach(step => {
                step.classList.remove('active', 'completed', 'error');
                const icon = step.querySelector('.step-icon i');
                icon.className = icon.getAttribute('data-icon') || 'fas fa-check';
            });
        }

        // 处理上传
        uploadBtn.addEventListener('click', async () => {
            const file = fileInput.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            try {
                uploadBtn.disabled = true;
                uploadBtn.textContent = '上传中...';
                progressContainer.style.display = 'block';
                loadingSpinner.style.display = 'block';
                
                // 开始上传
                updateStep(1, 'completed');
                updateStep(2, 'processing');
                updateProgress(0, '开始上传文件...');

                const xhr = new XMLHttpRequest();
                xhr.open('POST', '/api/process', true);

                // 监听上传进度
                xhr.upload.onprogress = (e) => {
                    if (e.lengthComputable) {
                        const percentComplete = (e.loaded / e.total) * 100;
                        updateProgress(percentComplete, '文件上传中...');
                    }
                };

                xhr.onload = async function () {
                    if (xhr.status === 200) {
                        const data = JSON.parse(xhr.responseText);
                        
                        // 上传完成，开始处理
                        updateStep(2, 'completed');
                        updateStep(3, 'processing');
                        updateProgress(50, '正在处理文件...');
                        
                        // 模拟处理过程
                        setTimeout(() => {
                            updateStep(3, 'completed');
                            updateStep(4, 'processing');
                            updateProgress(100, '处理完成！');
                            loadingSpinner.style.display = 'none';
                            uploadBtn.textContent = '上传';

                            result.className = 'success';
                            result.style.display = 'block';
                            result.innerHTML = `
                                <h3>上传成功！</h3>
                                <p>文件名：${file.name}</p>
                                <p>时长：${data.metadata.duration} 秒</p>
                                <p>采样率：${data.metadata.sample_rate} Hz</p>
                                <p>速度：${data.metadata.tempo} BPM</p>
                                <p>节拍数：${data.metadata.beats}</p>

                                <h4>分析结果：</h4>
                                <div class="analysis-results">
                                    <div class="result-item">
                                        <h5>波形图</h5>
                                        <img src="${data.output_files.waveform}" alt="波形图" onerror="this.onerror=null; this.src=''; this.alt='加载失败'">
                                    </div>
                                    <div class="result-item">
                                        <h5>频谱图</h5>
                                        <img src="${data.output_files.spectrogram}" alt="频谱图" onerror="this.onerror=null; this.src=''; this.alt='加载失败'">
                                    </div>
                                    <div class="result-item">
                                        <h5>音符信息</h5>
                                        <a href="${data.output_files.notes}" target="_blank">查看详细分析</a>
                                    </div>
                                </div>

                                <h4>音乐文件：</h4>
                                <div class="analysis-results">
                                    <div class="result-item">
                                        <h5>MIDI 文件</h5>
                                        <a href="${data.output_files.midi}" download>下载 MIDI 文件</a>
                                    </div>
                                    <div class="result-item">
                                        <h5>五线谱</h5>
                                        <a href="${data.output_files.musicxml}" download>下载 MusicXML 文件</a>
                                        ${data.output_files.pdf ? `<br><a href="${data.output_files.pdf}" download>下载 PDF 文件</a>` : ''}
                                    </div>
                                </div>
                            `;
                            
                            // 刷新历史记录
                            loadHistory();
                        }, 1500);
                    } else {
                        throw new Error('上传失败');
                    }
                };

                xhr.onerror = function () {
                    loadingSpinner.style.display = 'none';
                    uploadBtn.textContent = '上传';
                    updateStep(2, 'error');
                    result.className = 'error';
                    result.style.display = 'block';
                    result.innerHTML = '<h3>上传失败</h3><p>请检查网络连接后重试</p>';
                };

                xhr.send(formData);

            } catch (error) {
                loadingSpinner.style.display = 'none';
                uploadBtn.textContent = '上传';
                updateStep(2, 'error');
                result.className = 'error';
                result.style.display = 'block';
                result.innerHTML = `<h3>错误</h3><p>${error.message}</p>`;
            }
        });
    </script>
</body>

</html>
